package com.fenghuajueli.lib_pictureselect.activity;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.fenghuajueli.lib_pictureselect.constants.MediaType;
import com.fenghuajueli.lib_pictureselect.entity.SelectMediaEntity;
import com.fenghuajueli.lib_pictureselect.R;
import com.fenghuajueli.lib_pictureselect.adapter.PictureBottomPreviewItemAdapter;
import com.fenghuajueli.lib_pictureselect.adapter.PicturePagerAdapter;
import com.fenghuajueli.lib_pictureselect.adapter.SelectMediaTabAdapter;
import com.fenghuajueli.lib_pictureselect.config.PhotoConfig;
import com.fenghuajueli.lib_pictureselect.dialog.HandlerVideoDialog;
import com.fenghuajueli.lib_pictureselect.fragment.SelectAllFragment;
import com.fenghuajueli.lib_pictureselect.fragment.SelectPhotoFragment;
import com.fenghuajueli.lib_pictureselect.fragment.SelectVideoFragment;
import com.fenghuajueli.lib_pictureselect.interfaces.OnListItemListener;
import com.fenghuajueli.lib_pictureselect.utils.FileQUtils;
import com.fenghuajueli.lib_pictureselect.utils.HorizontalItemDecoration;
import com.fenghuajueli.lib_pictureselect.utils.MediaLoadManager;
import com.fenghuajueli.lib_pictureselect.utils.MediaSelectDataUtils;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class PictureSelectActivity extends BaseSelectActivity implements MaterialPreviewActivity.ChoiceMaterialListener {

    private MagicIndicator magicIndicator;
    private SelectMediaTabAdapter selectMediaTabAdapter;
    private List<String> tabTitleList;
    private ViewPager viewPager;
    private List<Fragment> fragmentList = new ArrayList<>();
    private PicturePagerAdapter picturePagerAdapter;
    private SelectPhotoFragment selectPhotoFragment;
    private SelectAllFragment selectAllFragment;
    private SelectVideoFragment selectVideoFragment;
    private TextView tvGoNext;
    private TextView tvCountTips;
    private TextView tvCanSelectCount;
    private ImageView ivClose;
    private RecyclerView bottomRecyclerView;
    private PictureBottomPreviewItemAdapter pictureBottomPreviewItemAdapter;
    private HandlerVideoDialog handlerVideoDialog;
    private String cachePath;
    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 500;
    private static long lastClickTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_select);
        initView();
        showLoadingDialog();
        cachePath = getExternalFilesDir(Environment.DIRECTORY_PICTURES).getPath() + File.separator;
        FileUtils.createOrExistsDir(cachePath);
        MediaSelectDataUtils.alreadySelectMediaEntityList.clear();
        MediaSelectDataUtils.allSelectMediaEntityList.clear();
        MediaSelectDataUtils.imageSelectMediaEntityList.clear();
        MediaSelectDataUtils.videoSelectMediaEntityList.clear();
        tabTitleList = new ArrayList<>();
        MediaSelectDataUtils.allSelectMediaEntityList = MediaLoadManager.loadAllMediaData(this, PhotoConfig.getInstance().getMode());
        if (PhotoConfig.getInstance().getMode() == PhotoConfig.Mode.VIDEO) {
            MediaSelectDataUtils.videoSelectMediaEntityList.addAll(MediaSelectDataUtils.allSelectMediaEntityList);
            tabTitleList.add(getString(R.string.select_tab_video));
            selectVideoFragment = SelectVideoFragment.newInstance();
            fragmentList.add(selectVideoFragment);
        } else if (PhotoConfig.getInstance().getMode() == PhotoConfig.Mode.PHOTO) {
            MediaSelectDataUtils.imageSelectMediaEntityList.addAll(MediaSelectDataUtils.allSelectMediaEntityList);
            tabTitleList.add(getString(R.string.select_tab_photo));
            selectPhotoFragment = SelectPhotoFragment.newInstance();
            fragmentList.add(selectPhotoFragment);
        } else {
            for (SelectMediaEntity selectMediaEntity : MediaSelectDataUtils.allSelectMediaEntityList) {
                if (selectMediaEntity.getType() == MediaType.Type.VIDEO) {
                    MediaSelectDataUtils.videoSelectMediaEntityList.add(selectMediaEntity);
                } else {
                    MediaSelectDataUtils.imageSelectMediaEntityList.add(selectMediaEntity);
                }
            }
            tabTitleList.add(getString(R.string.select_tab_all));
            tabTitleList.add(getString(R.string.select_tab_video));
            tabTitleList.add(getString(R.string.select_tab_photo));
            selectAllFragment = SelectAllFragment.newInstance();
            selectPhotoFragment = SelectPhotoFragment.newInstance();
            selectVideoFragment = SelectVideoFragment.newInstance();
            fragmentList.add(selectAllFragment);
            fragmentList.add(selectVideoFragment);
            fragmentList.add(selectPhotoFragment);
        }
        tvCountTips.setText(getString(R.string.select_count_photo_tips, PhotoConfig.getInstance().getMinCount()));
        tvCanSelectCount.setText(getString(R.string.select_can_count_photo_tips, PhotoConfig.getInstance().getMaxCount()));
        selectMediaTabAdapter = new SelectMediaTabAdapter(tabTitleList);
        selectMediaTabAdapter.setViewPager(viewPager);
        CommonNavigator navigator = new CommonNavigator(this);
        navigator.setAdapter(selectMediaTabAdapter);
        magicIndicator.setNavigator(navigator);
        picturePagerAdapter = new PicturePagerAdapter(getSupportFragmentManager(), fragmentList, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        viewPager.setAdapter(picturePagerAdapter);
        ViewPagerHelper.bind(magicIndicator, viewPager);
        hideLoadingDialog();
        initBottomAdapter();
    }

    private void initView() {
        magicIndicator = findViewById(R.id.magicIndicator);
        viewPager = findViewById(R.id.viewPager);
        tvGoNext = findViewById(R.id.tvGoNext);
        tvCountTips = findViewById(R.id.tvCountTips);
        tvCanSelectCount = findViewById(R.id.tvCanSelectCount);
        bottomRecyclerView = findViewById(R.id.bottomRecyclerView);
        ivClose = findViewById(R.id.ivClose);
        tvGoNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFastClick()) {
                    return;
                }
                if (MediaSelectDataUtils.alreadySelectMediaEntityList.size() < PhotoConfig.getInstance().getMinCount()) {
                    ToastUtils.showShort(getString(R.string.select_count_small_mincount, PhotoConfig.getInstance().getMinCount()));
                    return;
                }
                if (PhotoConfig.getInstance().getOnSelectResultListener() != null) {
                    List<SelectMediaEntity> resultList = new ArrayList<>();
                    for (SelectMediaEntity selectMediaEntity : MediaSelectDataUtils.alreadySelectMediaEntityList) {
                        resultList.add(selectMediaEntity.cloneThis());
                    }
                    if (PhotoConfig.getInstance().isCopyToPrivate()) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            moveVideo(resultList);
                        } else {
                            callBack(resultList);
                        }
                    } else {
                        callBack(resultList);
                    }
                }

            }
        });
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 不进行copy时 设置androidQpath为原始路径
     *
     * @param resultList
     */
    private void callBack(List<SelectMediaEntity> resultList) {
        for (SelectMediaEntity selectMediaEntity : resultList) {
            selectMediaEntity.setAndroidQPath(selectMediaEntity.getPath());
        }
        PhotoConfig.getInstance().getOnSelectResultListener().onResult(resultList);
        PhotoConfig.getInstance().setOnSelectResultListener(null);
        finish();
    }

    private void showHandlerDialog() {
        if (handlerVideoDialog != null) {
            handlerVideoDialog.dismiss();
            handlerVideoDialog = null;
        }
        handlerVideoDialog = new HandlerVideoDialog(PictureSelectActivity.this);
        handlerVideoDialog.setCancelable(false);
        handlerVideoDialog.show();
    }

    private void hideHandlerDialog() {
        if (handlerVideoDialog != null) {
            handlerVideoDialog.dismiss();
            handlerVideoDialog = null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshAllPosition();
        refreshPhotoPosition();
        refreshVideoPosition();
    }

    private void moveVideo(List<SelectMediaEntity> resultList) {
        showHandlerDialog();
        Observable.create(new ObservableOnSubscribe<Boolean>() {

            @Override
            public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
                boolean isSuccess = true;
                //将文件拷贝到缓存目录使用
                for (int i = 0; i < resultList.size(); i++) {
                    SelectMediaEntity selectMediaEntity = resultList.get(i);
                    LogUtils.d("选择文件的地址：" + selectMediaEntity.getPath());
                    String filePath = cachePath + selectMediaEntity.getMediaName();
                    File file = new File(filePath);
                    if (!file.exists()) {
                        String path = FileQUtils.moveFileToPrivate(PictureSelectActivity.this, Uri.parse(resultList.get(i).getUri()), cachePath);
                        if (TextUtils.isEmpty(path)) {
                            isSuccess = false;
                            break;
                        } else {
                            resultList.get(i).setAndroidQPath(path);
                        }
                    } else {
                        LogUtils.d("文件大小：" + file.length() + "---->" + selectMediaEntity.getSize());
                        if (file.length() == selectMediaEntity.getSize()) {
                            resultList.get(i).setAndroidQPath(filePath);
                            LogUtils.d("文件已经存在不需要在拷贝-------------》" + selectMediaEntity.getMediaName());
                        } else {
                            String path = FileQUtils.moveFileToPrivate(PictureSelectActivity.this, Uri.parse(resultList.get(i).getUri()), cachePath);
                            if (TextUtils.isEmpty(path)) {
                                isSuccess = false;
                                break;
                            } else {
                                resultList.get(i).setAndroidQPath(path);
                            }
                            LogUtils.d("文件已经存在但不完整-------------》" + selectMediaEntity.getMediaName());
                        }
                    }
                    setProgress((int) ((i / (double) resultList.size()) * 100), i);
                }
                emitter.onNext(isSuccess);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean isSuccess) {
                        if (isSuccess) {
                            hideHandlerDialog();
                            PhotoConfig.getInstance().getOnSelectResultListener().onResult(resultList);
                            PhotoConfig.getInstance().setOnSelectResultListener(null);
                            finish();
                        } else {
                            hideHandlerDialog();
                            ToastUtils.showShort("素材选择失败，请重试！");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 设置进度
     *
     * @param progress
     * @param currentPosition
     */
    public void setProgress(int progress, int currentPosition) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (handlerVideoDialog != null) {
                    handlerVideoDialog.setProgress(progress, currentPosition);
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        MediaSelectDataUtils.imageSelectMediaEntityList.clear();
        MediaSelectDataUtils.videoSelectMediaEntityList.clear();
        MediaSelectDataUtils.alreadySelectMediaEntityList.clear();
        MediaSelectDataUtils.allSelectMediaEntityList.clear();
        hideLoadingDialog();
        hideHandlerDialog();
    }

    private void initBottomAdapter() {
        pictureBottomPreviewItemAdapter = new PictureBottomPreviewItemAdapter(this, MediaSelectDataUtils.alreadySelectMediaEntityList);
        pictureBottomPreviewItemAdapter.setOnItemClickListener(new OnListItemListener<SelectMediaEntity>() {
            @Override
            public void onItemClick(int position, SelectMediaEntity data) {
                refreshPhotoPosition();
                refreshVideoPosition();
                refreshAllPosition();
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(RecyclerView.HORIZONTAL);
        bottomRecyclerView.addItemDecoration(new HorizontalItemDecoration(ConvertUtils.dp2px(12)));
        bottomRecyclerView.setLayoutManager(layoutManager);
        bottomRecyclerView.setAdapter(pictureBottomPreviewItemAdapter);
    }


    public void refreshAllPosition() {
        if (selectAllFragment != null) {
            selectAllFragment.refreshPosition();
        }
        setStatus();
    }


    public void refreshPhotoPosition() {
        if (selectPhotoFragment != null) {
            selectPhotoFragment.refreshPosition();
        }
        setStatus();
    }


    public void refreshVideoPosition() {
        if (selectVideoFragment != null) {
            selectVideoFragment.refreshPosition();
        }
        setStatus();
    }

    private void setStatus() {
        if (MediaSelectDataUtils.alreadySelectMediaEntityList.size() > 0) {
            bottomRecyclerView.setVisibility(View.VISIBLE);
            tvGoNext.setSelected(true);
            tvGoNext.setTextColor(Color.parseColor("#3C3216"));
        } else {
            bottomRecyclerView.setVisibility(View.GONE);
            tvGoNext.setSelected(false);
            tvGoNext.setTextColor(Color.parseColor("#a0a0a0"));
        }
        if (pictureBottomPreviewItemAdapter != null) {
            pictureBottomPreviewItemAdapter.refreshData(MediaSelectDataUtils.alreadySelectMediaEntityList);
        }
    }

    public boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) <= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    public void goPreview(int type, int position) {
        MaterialPreviewActivity.choiceMaterialListener = this;
        MaterialPreviewActivity.start(this, type, position);
    }

    @Override
    public void onChoiceChange() {
        refreshAllPosition();
        refreshPhotoPosition();
        refreshVideoPosition();
        setStatus();
    }
}